package com.ruoyi.web.controller.demo.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.WxworkOmsRelationModel;
import com.ruoyi.system.mapper.WxworkOmsRelationMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Author hnb
 * @Date 2024/9/30
 * @Description 德晨对接微信-获取人员打卡信息
 **/

@RestController
@RequestMapping("/fromContent")
public class DechenFormContentController extends BaseController {

    @Autowired
    private WxworkOmsRelationMapper wxworkOmsRelationMapper;
    private static final Logger log = LoggerFactory.getLogger(DechenFormContentController.class);

    @Value("${getUrl}")
    private String getUrl;
    @Value("${getcheckUrl}")
    private String getcheckUrl;
    @Value("${setcheckUrl}")
    private String setcheckUrl;
    @Value("${corpid}")
    private String corpid;
    @Value("${corpsecret}")
    private String corpsecret;
    @Value("${punchCorrection}")
    private String punchCorrection;
    @Value("${addCheckinRecord}")
    private String addCheckinRecord;
    @Value("${applyevent}")
    private String applyevent;

    /**
     * 获取token
     * @return
     */
    @Log(title = "获取token", businessType = BusinessType.OTHER)
    @GetMapping("/getToken")
    public String getToken(){
        String param = "corpid="+corpid+"&corpsecret="+corpsecret;
        log.error("获取token传参:{}", param);
        String sendGet = HttpUtils.sendGet(getUrl, param);
        log.error("获取token结果:{}", sendGet);
        return sendGet;
    }

    /**
     * 获取打卡人员排班信息
     * @return
     */
    @Log(title = "获取打卡人员排班信息", businessType = BusinessType.OTHER)
    @PostMapping("/getcheck")
    public AjaxResult getcheck(@RequestBody Map param){
        String token = getToken();
        JSONObject jsonObject = JSON.parseObject(token);
        if(jsonObject.get("errmsg").equals("ok")&& !ObjectUtils.isEmpty(jsonObject.get("access_token"))){
            String access_token = String.valueOf(jsonObject.get("access_token"));
            String url = getcheckUrl+"?access_token="+access_token;
            String sendGet = HttpUtils.sendPost(url, null);
            log.error("获取打卡人员排班信息结果:{}", sendGet);
            JSONObject object = JSON.parseObject(sendGet);
            if(!ObjectUtils.isEmpty(param.get("groupid"))){
                JSONArray group = (JSONArray) object.get("group");
                for (Object groupId : group) {
                    Map<String,Object> map = (Map<String,Object>)groupId;
                    String groupId1 = String.valueOf(map.get("groupid"));
                    if(!StringUtils.isEmpty(groupId1)&&groupId1.equals(param.get("groupid"))){
                        List<Object> schedulelist = (List<Object>)map.get("schedulelist");
                        return success(schedulelist);
                    }
                }
            }
            if(object.get("errmsg").equals("ok")&&!ObjectUtils.isEmpty(object.get("group"))){
                return success(object.get("group"));
            }else {
                log.error("获取打卡人员排班错误信息:{}", String.valueOf(jsonObject.get("errmsg")));
                return error("获取信息错误！");
            }
        }else {
            log.error("获取打卡人员排班错误信息:{}", String.valueOf(jsonObject.get("errmsg")));
            return error(String.valueOf(jsonObject.get("errmsg")));
        }
    }

    /**
     * 修改排班信息
     * @param map
     * @return
     */
    @Log(title = "修改排班信息", businessType = BusinessType.OTHER)
    @PostMapping("/setcheck")
    public AjaxResult setcheck(@RequestBody Map map){
        String token = getToken();
        JSONObject jsonObject = JSON.parseObject(token);
        if(jsonObject.get("errmsg").equals("ok")&& !ObjectUtils.isEmpty(jsonObject.get("access_token"))){
            String access_token = String.valueOf(jsonObject.get("access_token"));
            String url = setcheckUrl+"?access_token="+access_token;

            List<Object> items = (List<Object>) map.get("items");
            Map<String,String> user = (Map<String,String>)items.get(0);
            String userid = user.get("userid");
            WxworkOmsRelationModel wxworkOmsRelationModel = wxworkOmsRelationMapper.selectById(userid);
            System.out.println("获取用户信息："+wxworkOmsRelationModel);
            if(ObjectUtils.isEmpty(wxworkOmsRelationModel)||StringUtils.isEmpty(wxworkOmsRelationModel.getFdAppPkId())){
                return error("获取用户信息错误！");
            }
            String fdAppPkId = wxworkOmsRelationModel.getFdAppPkId();

            Map<String,String> item = new HashMap<>();
            item.put("userid",fdAppPkId);
            item.put("day",user.get("day"));
            item.put("schedule_id",user.get("schedule_id"));
            Map<String, Object> map1 = new HashMap<>();
            map1.put("groupid",map.get("groupid"));
            map1.put("items",item);
            map1.put("yearmonth",map.get("yearmonth"));
            String param = JSONObject.toJSONString(map1);
            log.error("修改排班信息传参:{}", param);
            String sendGet = HttpUtils.sendPost(url, param);
            log.error("修改排班信息结果:{}", sendGet);
            return success(sendGet);
        }else {
            log.error("修改排班错误信息:{}", String.valueOf(jsonObject.get("errmsg")));
            return error(String.valueOf(jsonObject.get("errmsg")));
        }
    }
    /**
     * 添加打卡记录
     * @param map
     * @return
     */
    @Log(title = "添加打卡记录", businessType = BusinessType.OTHER)
    @PostMapping("/addCheckinRecord")
    public AjaxResult addCheckinRecord(@RequestBody Map map) {
        try {
            String token = getToken();
            JSONObject jsonObject = JSON.parseObject(token);
            if (jsonObject.get("errmsg").equals("ok") && !ObjectUtils.isEmpty(jsonObject.get("access_token"))) {
                String access_token = String.valueOf(jsonObject.get("access_token"));
                String url = addCheckinRecord + "?access_token=" + access_token;

                String userid = (String) map.get("userid");
                WxworkOmsRelationModel wxworkOmsRelationModel = wxworkOmsRelationMapper.selectById(userid);
                System.out.println("获取用户信息：" + wxworkOmsRelationModel);
                if (ObjectUtils.isEmpty(wxworkOmsRelationModel) || StringUtils.isEmpty(wxworkOmsRelationModel.getFdAppPkId())) {
                    return error("获取用户信息错误！");
                }
                String fdAppPkId = wxworkOmsRelationModel.getFdAppPkId();

                Map<String, Object> item = new HashMap<>();
                item.put("userid", fdAppPkId);
                // 增加参数校验
                String checkinTime = (String) map.get("checkinTime");
                if (StringUtils.isEmpty(checkinTime)) {
                    return error("缺少必要参数：checkinTime");
                }
                // 日期解析增加异常捕获
                try {
                    long timestamp = DateUtil.parse(checkinTime, "EEE MMM dd HH:mm:ss zzz yyyy", Locale.US).getTime()/1000;
                    item.put("checkin_time", timestamp);
                } catch (Exception e) {
                    log.error("日期格式解析失败: {}", checkinTime, e);
                    return error("日期格式不正确，示例：Thu Mar 06 07:49:00 CST 2025");
                }
                item.put("location_title", "德晨能源");
                item.put("location_detail", "德晨能源");
                item.put("device_type", 3);  // 使用数字而不是字符串
                item.put("device_detail", "其他补卡");

                List<Map<String, Object>> recordsList = new ArrayList<>();
                recordsList.add(item);

                Map<String, Object> map1 = new HashMap<>();
                map1.put("records", recordsList);
                String param = JSONObject.toJSONString(map1);
                log.error("打卡人员补卡信息传参:{}", param);
                String sendGet = HttpUtils.sendPost(url, param);
                log.error("打卡人员补卡信息结果:{}", sendGet);
                return success(sendGet);
            } else {
                log.error("打卡人员补卡错误信息:{}", String.valueOf(jsonObject.get("errmsg")));
                return error(String.valueOf(jsonObject.get("errmsg")));
            }
        } catch (NullPointerException e) {
            log.error("空指针异常: ", e);
            return error("请求参数不完整");
        } catch (Exception e) {
            log.error("补卡操作异常: ", e);
            return error("系统处理异常");
        }
    }
    /**
     * 提交审批申请
     * @param map
     * @return
     */
    @Log(title = "提交审批申请", businessType = BusinessType.OTHER)
    @PostMapping("/applyevent")
    public AjaxResult applyevent(@RequestBody Map map) {
        try {
            String token = getToken();
            JSONObject jsonObject = JSON.parseObject(token);
            if (jsonObject.get("errmsg").equals("ok") && !ObjectUtils.isEmpty(jsonObject.get("access_token"))) {
                String access_token = String.valueOf(jsonObject.get("access_token"));
                String url = applyevent + "?access_token=" + access_token;

                String userid = (String) map.get("userid");
                WxworkOmsRelationModel wxworkOmsRelationModel = wxworkOmsRelationMapper.selectById(userid);
                System.out.println("获取用户信息：" + wxworkOmsRelationModel);
                if (ObjectUtils.isEmpty(wxworkOmsRelationModel) || StringUtils.isEmpty(wxworkOmsRelationModel.getFdAppPkId())) {
                    return error("获取用户信息错误！");
                }
                String fdAppPkId = wxworkOmsRelationModel.getFdAppPkId();

                String param = "{\n" +
                        "  \"creator_userid\": \"18365695989\",\n" +
                        "  \"template_id\": \"3WN5uZiSaJsxtypgtHTa61QCzaT4DLLBCVMaiBnc\",\n" +
                        "  \"use_template_approver\": 1,\n" +
                        "  \"apply_data\": {\n" +
                        "    \"contents\": [{\n" +
                        "        \"control\": \"Selector\",\n" +
                        "        \"id\": \"Selector-1723075883959\",\n" +
                        "        \"title\": [{\n" +
                        "          \"text\": \"层级\",\n" +
                        "          \"lang\": \"zh_CN\"\n" +
                        "        }],\n" +
                        "        \"value\": {\n" +
                        "          \"selector\": {\n" +
                        "            \"type\": \"single\",\n" +
                        "            \"options\": [{\n" +
                        "              \"key\": \"option-1723075883959\",\n" +
                        "              \"value\": [{\n" +
                        "                \"text\": \"员工\",\n" +
                        "                \"lang\": \"zh_CN\"\n" +
                        "              }]\n" +
                        "            }]\n" +
                        "          }\n" +
                        "        },\n" +
                        "        \"display\": 1,\n" +
                        "        \"require\": 1\n" +
                        "      },\n" +
                        "      {\n" +
                        "        \"control\": \"Text\",\n" +
                        "        \"id\": \"Text-1723076079610\",\n" +
                        "        \"title\": [{\n" +
                        "          \"text\": \"联系电话\",\n" +
                        "          \"lang\": \"zh_CN\"\n" +
                        "        }],\n" +
                        "        \"value\": {\n" +
                        "          \"text\": \"1\"\n" +
                        "        },\n" +
                        "        \"display\": 1,\n" +
                        "        \"require\": 1\n" +
                        "      },\n" +
                        "      {\n" +
                        "        \"control\": \"Vacation\",\n" +
                        "        \"id\": \"vacation-1563793073898\",\n" +
                        "        \"title\": [{\n" +
                        "            \"text\": \"请假类型\",\n" +
                        "            \"lang\": \"zh_CN\"\n" +
                        "          },\n" +
                        "          {\n" +
                        "            \"text\": \"Leave Type\",\n" +
                        "            \"lang\": \"en\"\n" +
                        "          }\n" +
                        "        ],\n" +
                        "        \"value\": {\n" +
                        "          \"vacation\": {\n" +
                        "            \"selector\": {\n" +
                        "              \"type\": \"single\",\n" +
                        "              \"options\": [{\n" +
                        "                \"key\": \"3\",\n" +
                        "                \"value\": [{\n" +
                        "                  \"text\": \"病假\",\n" +
                        "                  \"lang\": \"zh_CN\"\n" +
                        "                }]\n" +
                        "              }]\n" +
                        "            },\n" +
                        "            \"attendance\": {\n" +
                        "              \"date_range\": {\n" +
                        "                \"type\": \"hour\",\n" +
                        "                \"new_begin\": 1747455608,\n" +
                        "                \"new_end\": 1747455708,\n" +
                        "                \"new_duration\": 13320\n" +
                        "              },\n" +
                        "              \"type\": 1\n" +
                        "            }\n" +
                        "          }\n" +
                        "        },\n" +
                        "        \"display\": 1,\n" +
                        "        \"require\": 1\n" +
                        "      },\n" +
                        "      {\n" +
                        "        \"control\": \"Tips\",\n" +
                        "        \"id\": \"Tips-1723451336982\",\n" +
                        "        \"title\": [{\n" +
                        "          \"text\": \"说明\",\n" +
                        "          \"lang\": \"zh_CN\"\n" +
                        "        }],\n" +
                        "        \"value\": {\n" +
                        "          \"new_tips\": {\n" +
                        "            \"tips_content\": [{\n" +
                        "              \"text\": {\n" +
                        "                \"sub_text\": [{\n" +
                        "                  \"type\": 1,\n" +
                        "                  \"content\": {\n" +
                        "                    \"plain_text\": {\n" +
                        "                      \"content\": \"如果发起调休，请填写以下两个控件\"\n" +
                        "                    }\n" +
                        "                  }\n" +
                        "                }]\n" +
                        "              },\n" +
                        "              \"lang\": \"zh_CN\"\n" +
                        "            }]\n" +
                        "          }\n" +
                        "        },\n" +
                        "        \"display\": 1,\n" +
                        "        \"require\": 0\n" +
                        "      },\n" +
                        "      {\n" +
                        "        \"control\": \"Date\",\n" +
                        "        \"id\": \"Date-1723451180343\",\n" +
                        "        \"title\": [{\n" +
                        "          \"text\": \"调休开始时间(应休)\",\n" +
                        "          \"lang\": \"zh_CN\"\n" +
                        "        }],\n" +
                        "        \"value\": {\n" +
                        "          \"date\": {\n" +
                        "            \"type\": \"hour\",\n" +
                        "            \"s_timestamp\": \"\"\n" +
                        "          }\n" +
                        "        },\n" +
                        "        \"display\": 1,\n" +
                        "        \"require\": 0\n" +
                        "      },\n" +
                        "      {\n" +
                        "        \"control\": \"Date\",\n" +
                        "        \"id\": \"Date-1723451253792\",\n" +
                        "        \"title\": [{\n" +
                        "          \"text\": \"调休结束时间(应休)\\t\",\n" +
                        "          \"lang\": \"zh_CN\"\n" +
                        "        }],\n" +
                        "        \"value\": {\n" +
                        "          \"date\": {\n" +
                        "            \"type\": \"hour\",\n" +
                        "            \"s_timestamp\": \"\"\n" +
                        "          }\n" +
                        "        },\n" +
                        "        \"display\": 1,\n" +
                        "        \"require\": 0\n" +
                        "      },\n" +
                        "      {\n" +
                        "        \"control\": \"Text\",\n" +
                        "        \"id\": \"Text-1723076048175\",\n" +
                        "        \"title\": [{\n" +
                        "          \"text\": \"本月累计请假天数\",\n" +
                        "          \"lang\": \"zh_CN\"\n" +
                        "        }],\n" +
                        "        \"value\": {\n" +
                        "          \"text\": \"\"\n" +
                        "        },\n" +
                        "        \"display\": 1,\n" +
                        "        \"require\": 0\n" +
                        "      },\n" +
                        "      {\n" +
                        "        \"control\": \"Textarea\",\n" +
                        "        \"id\": \"item-1497581399901\",\n" +
                        "        \"title\": [{\n" +
                        "            \"text\": \"请假事由\",\n" +
                        "            \"lang\": \"zh_CN\"\n" +
                        "          },\n" +
                        "          {\n" +
                        "            \"text\": \"Leave Reason\",\n" +
                        "            \"lang\": \"en\"\n" +
                        "          }\n" +
                        "        ],\n" +
                        "        \"value\": {\n" +
                        "          \"text\": \"测试\"\n" +
                        "        },\n" +
                        "        \"display\": 1,\n" +
                        "        \"require\": 1\n" +
                        "      },\n" +
                        "      {\n" +
                        "        \"control\": \"File\",\n" +
                        "        \"id\": \"item-1497581426169\",\n" +
                        "        \"title\": [{\n" +
                        "            \"text\": \"附件上传\",\n" +
                        "            \"lang\": \"zh_CN\"\n" +
                        "          },\n" +
                        "          {\n" +
                        "            \"text\": \"Attachment\",\n" +
                        "            \"lang\": \"en\"\n" +
                        "          }\n" +
                        "        ],\n" +
                        "        \"value\": {\n" +
                        "        },\n" +
                        "        \"display\": 1\n" +
                        "      }\n" +
                        "    ]\n" +
                        "  },\n" +
                        "  \"comments\": [],\n" +
                        "  \"process_list\": {\n" +
                        "    \"node_list\": [{\n" +
                        "      \"node_type\": 2,\n" +
                        "      \"sub_node_list\": [{\n" +
                        "        \"userid\": \"18365695989\"\n" +
                        "      }]\n" +
                        "    }]\n" +
                        "  },\n" +
                        "  \"summary_list\": [{\n" +
                        "      \"summary_info\": [{\n" +
                        "        \"text\": \"摘要第1行\",\n" +
                        "        \"lang\": \"zh_CN\"\n" +
                        "      }]\n" +
                        "    },\n" +
                        "    {\n" +
                        "      \"summary_info\": [{\n" +
                        "        \"text\": \"摘要第2行\",\n" +
                        "        \"lang\": \"zh_CN\"\n" +
                        "      }]\n" +
                        "    },\n" +
                        "    {\n" +
                        "      \"summary_info\": [{\n" +
                        "        \"text\": \"摘要第3行\",\n" +
                        "        \"lang\": \"zh_CN\"\n" +
                        "      }]\n" +
                        "    }\n" +
                        "  ],\n" +
                        "  \"node_list\": [{\n" +
                        "    \"node_type\": 2,\n" +
                        "    \"sub_node_list\": [{\n" +
                        "      \"userid\": \"18365695989\",\n" +
                        "      \"media_ids\": []\n" +
                        "    }]\n" +
                        "  }]\n" +
                        "}";
//                String param = JSONObject.toJSONString(map1);
                log.error("请假流程申请传参:{}", param);
                String sendGet = HttpUtils.sendPost(url, param);
                log.error("请假流程申请结果:{}", sendGet);
                return success(sendGet);
            } else {
                log.error("请假流程申请错误信息:{}", String.valueOf(jsonObject.get("errmsg")));
                return error(String.valueOf(jsonObject.get("errmsg")));
            }
        } catch (NullPointerException e) {
            log.error("空指针异常: ", e);
            return error("请求参数不完整");
        } catch (Exception e) {
            log.error("补卡操作异常: ", e);
            return error("系统处理异常");
        }
    }
}
